#!/bin/sh

. /lib/functions.sh

blkdev=`dirname $DEVPATH`
device=`basename $DEVPATH`

STORAGE_PATH_PREFIX="/tmp/storage"

nand_find_ubi() {
	local ubidevdir ubidev mtdnum
	mtdnum="$( find_mtd_index $1 )"
	[ ! "$mtdnum" ] && return 1
	for ubidevdir in /sys/devices/virtual/ubi/ubi*; do
		[ ! -d "$ubidevdir" ] && continue
		cmtdnum="$( cat $ubidevdir/mtd_num )"
		[ ! "$mtdnum" ] && continue
		if [ "$mtdnum" = "$cmtdnum" ]; then
			ubidev=$( basename $ubidevdir )
			ubi_mknod "$ubidevdir"
			echo $ubidev
			return 0
		fi
	done
}

case "$device" in
"sd"* | "mmcblk"*)
	mount_point="$STORAGE_PATH_PREFIX/$device"
	case "$ACTION" in
	add)
		ID_FS_TYPE=""
		ID_FS_UUID=""
		dev_path="/dev/$device"

		logger -t "storage" "start with $dev_path"
		eval `blkid -o udev $dev_path`

		# no filesystem type
		[ -z $ID_FS_TYPE ] && {
			logger -t "storage" "$dev_path no filesystem"

			return 0
		}

		mkdir -p $mount_point

		if [ "$ID_FS_TYPE" == "msdos" -o "$ID_FS_TYPE" == "vfat" ] ; then
			mount -t vfat -o noatime,fmask=0000,dmask=0000,iocharset=utf8 $dev_path $mount_point
		elif [ "$ID_FS_TYPE" == "ntfs" ] ; then
			ntfs-3g -o big_writes,noatime,nls=utf8 $dev_path $mount_point
		elif [ "$ID_FS_TYPE" == "exfat" ] ; then
			mount -t exfat -o noatime,fmask=0,dmask=0,iocharset=utf8 $dev_path $mount_point
		elif [ "$ID_FS_TYPE" == "ext4" -o "$ID_FS_TYPE" == "ext3" -o "$ID_FS_TYPE" == "ext2" ] ; then
			mount -o noatime $dev_path $mount_point
		elif [ "$ID_FS_TYPE" == "f2fs" ] ; then
			mount -t f2fs -o noatime $dev_path $mount_point
		fi

		if [ $? -eq "0" ]; then
			case "$device" in
			"mmcblk"*)
				start_istorage $mount_point
				;;
			esac
		else
			logger -t "storage" "$dev_path mount failed($ID_FS_TYPE)"
		fi
		;;
	remove)
		mount | grep -qs "$mount_point"
		if [ $? -eq 0 ]; then
			case "$device" in
			"mmcblk"*)
				stop_istorage
				;;
			esac

			logger -t "storage" "umount $dev_path $mount_point"

			#fuser -m -k $mount_point
			umount -l $dev_path $mount_point
		fi
		;;
	esac
	;;
"mtdblock"*)
	case "$ACTION" in
	add)
		optindex=$(find_mtd_index "opt")
		if [ -z "$optindex" ]; then
			exit 0
		fi

		if [ "$device" != "mtdblock$optindex" ]; then
			exit 0
		fi

		ubidetach -m $optindex

		ubiattach /dev/ubi_ctrl -m $optindex

		if [ "$?" -eq 0 ]; then
			ubidev=$(nand_find_ubi "opt")
			mkdir -p /opt
			mount -t ubifs $ubidev:opt /opt
			if [ "$?" -ne 0 ]; then
				logger -t storage "mount $device(/dev/mtd$optindex) failed, remake ubifs($ubidev)"
				ubidetach -m $optindex
				flash_erase /dev/mtd$optindex 0 0
				ubiattach /dev/ubi_ctrl -m $optindex
				ubimkvol /dev/$ubidev -N opt -m
				mount -t ubifs $ubidev:opt /opt
			fi
		else
			logger -t storage "attach $device failed"
			flash_erase /dev/mtd$optindex 0 0
			ubiattach /dev/ubi_ctrl -m $optindex
			ubidev=$(nand_find_ubi "opt")
			mkdir -p /opt
			ubimkvol /dev/$ubidev -N opt -m
			mount -t ubifs $ubidev:opt /opt
		fi
		;;
	remove)
		sync
		umount /opt
		ubidetach -m $optindex
		;;
	esac
esac

